//
//  CPHomeViewController.m
//  ChinaPoem
//
//  Created by 赵俊明 on 2019/3/4.
//  Copyright © 2019 赵俊明. All rights reserved.
//

#import "CPHomeViewController.h"
#import "CPHomeCell.h"
#import "PYSearch.h"
#import "UIViewController+MMDrawerController.h"
#import "MMDrawerBarButtonItem.h"
#import "CPContentController.h"
@interface CPHomeViewController ()<PYSearchViewControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>
@property (nonatomic, weak) UIView *backView;
@property (nonatomic, weak) UICollectionView *collection;
@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation CPHomeViewController

static NSString *ids = @"cell";

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"诗词";
    self.LImage = @"sort";
    self.RImage = @"search";
    UICollectionViewFlowLayout *collectionLayout = [[UICollectionViewFlowLayout alloc] init];
    UICollectionView *collection = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:collectionLayout];
    collection.backgroundColor = [UIColor clearColor];
    collection.dataSource = self;
    collection.delegate = self;
    collection.showsVerticalScrollIndicator = NO;
    [collection registerClass:[CPHomeCell class] forCellWithReuseIdentifier:ids];
    [self.view addSubview:collection];
    self.collection = collection;
    [collection mas_makeConstraints:^(MASConstraintMaker *make) {
        if (@available(iOS 11.0, *)) {
            make.top.mas_equalTo(self.view.mas_safeAreaLayoutGuideTop);
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.top.mas_equalTo(self.view.mas_top);
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }
        make.width.mas_equalTo(self.view);
    }];
    [self cp_pullRefresh];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CPHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ids forIndexPath:indexPath];
    cell.model = _dataSource[indexPath.row];
    return cell;
}

#pragma mark UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CPContentController *content = [CPContentController new];
    content.model = _dataSource[indexPath.row];
    content.title = content.model.cp_title;
    [self.navigationController pushViewController:content animated:YES];
}

#pragma mark UICollectionViewDataSource,
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

#pragma mark UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.view.width-14, 104);
}

// 动态设置每个分区的EdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(8, 7, 5, 7);
}

// 动态设置每行的间距大小
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 7;
}

- (void)cp_leftBtn
{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

- (void)cp_rightBtn
{
    // 1.创建热门搜索
    NSMutableArray *hots = [[CPSQLTools cp_sharedInstance]  cp_search:@"poems" column:@"title"];
    NSString *placholder = @"输入搜索诗词名字";
    JMSelf(ws);
    PYSearchViewController *sVC = [PYSearchViewController searchViewControllerWithHotSearches:hots searchBarPlaceholder:placholder didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        NSArray *titles = [searchText componentsSeparatedByString:@"-"];
        NSString *sql = [NSString stringWithFormat:@"select * from poems where title = '%@';", titles.firstObject];
        NSMutableArray *models = [[CPSQLTools cp_sharedInstance] cp_query_poem:sql];
        if (models.count > 0) {
            CPContentController *content = [CPContentController new];
            content.model = models.firstObject;
            content.title = content.model.title;
            [searchViewController.navigationController pushViewController:content animated:YES];
        }else{
            [ws cp_show:@"很抱歉，没有找到！" msg:@"没有找到" cancel:NO handle:^(BOOL isLive) {}];
        }
    }];
    sVC.hotSearchStyle = PYHotSearchStyleDefault; // 热门搜索风格根据选择
    sVC.searchHistoryStyle = PYHotSearchStyleDefault; // 搜索历史风格为default
    sVC.delegate = self;
    CPNavController *nav = [[CPNavController alloc] initWithRootViewController:sVC];
    [self presentViewController:nav animated:YES completion:nil];
}

#pragma mark - PYSearchViewControllerDelegate
- (void)searchViewController:(PYSearchViewController *)searchViewController searchTextDidChange:(UISearchBar *)seachBar searchText:(NSString *)searchText
{
    if (searchText.length) { // 与搜索条件再搜索
        NSString *sql = @"select * from poems where title like ?";
        NSString *name = [NSString stringWithFormat:@"%%%@%%", searchText];
        searchViewController.searchSuggestions = [[CPSQLTools cp_sharedInstance] cp_searchPoem:sql likeName:name column:@"title"];
    }
}

- (void)cp_pullRefresh
{
    // 下拉刷新
    JMSelf(weakSelf);
    self.collection.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.dataSource = [[CPSQLTools cp_sharedInstance] cp_query_poem:@"select * from poems order by random() limit 50;"];
        sleep(.9);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.collection reloadData];
            [weakSelf.collection.mj_header endRefreshing];
        });
    }];

    [self.collection.mj_header beginRefreshing];
}

@end
